const http = require('http')

function makeRequest (url) {
  return new Promise((resolve, reject) => {
    const request = http.get(url, response => {
      let data = ''

      response.on('data', chunk => {
        data += chunk
      })

      response.on('end', () => {
        try {
          const jsonData = JSON.parse(data)
          resolve({ data: jsonData, status: response.statusCode })
        } catch (error) {
          resolve({ data: data, status: response.statusCode })
        }
      })
    })

    request.on('error', error => {
      reject(error)
    })

    request.setTimeout(5000, () => {
      request.destroy()
      reject(new Error('请求超时'))
    })
  })
}

async function testUserAPI () {
  console.log('🧪 测试用户管理API...\n')

  try {
    // 1. 测试健康检查
    console.log('1. 测试健康检查...')
    const healthResponse = await makeRequest('http://localhost:3000/health')
    console.log('✅ 健康检查通过:', healthResponse.data.message)

    // 2. 测试获取用户列表
    console.log('\n2. 测试获取用户列表...')
    const usersResponse = await makeRequest('http://localhost:3000/api/users')
    console.log('✅ 用户列表获取成功, 用户数量:', usersResponse.data.total)
    console.log(
      '   示例用户:',
      usersResponse.data.users?.[0]?.email || '无用户'
    )

    // 3. 测试获取用户统计
    console.log('\n3. 测试获取用户统计...')
    const statsResponse = await makeRequest(
      'http://localhost:3000/api/users/stats'
    )
    console.log('✅ 用户统计获取成功:', {
      总用户数: statsResponse.data.totalUsers,
      活跃用户: statsResponse.data.activeUsers,
      VIP用户: statsResponse.data.vipUsers
    })

    console.log('\n🎉 用户管理API测试完成！数据库连接正常。')
  } catch (error) {
    console.error('❌ API测试失败:', error.message)
    if (error.code === 'ECONNREFUSED') {
      console.log('\n💡 建议: 请确保后端服务器已启动')
      console.log('   运行: cd server && npm start')
    }
  }
}

// 运行测试
testUserAPI()
